#include "changeformat.h"
#include "skbuff.h"
#include "eth.h"
#include "arp.h"
#include "ip.h"
#include "udp.h"
#include "utils.h"
#include "2410lib.h"

char TftpLoadEnd;
char TftpPutBegin;
char TftpPutMark;
extern char format_time[20];
int net_handle(void)
{
	struct sk_buff *skb;
	struct ethhdr *eth_hdr;												
	skb = alloc_skb(ETH_FRAME_LEN);

	if (eth_rcv(skb) != -1) 
	{

		eth_hdr = (struct ethhdr *)(skb->data);					
		skb_pull(skb, ETH_HLEN);
		if (ntohs(eth_hdr->h_proto) == ETH_P_ARP)
		{
			arp_rcv_packet(skb);

		}

		else if(ntohs(eth_hdr->h_proto) == ETH_P_IP)						
		{

		 	ip_rcv_packet(skb);

		}
	 	
	}

	free_skb(skb);

	return 0;
}



#define	LOCAL_IP_ADDR	((192UL<<24)|(168<<16)|(2<<8)|111)
#define	REMOTE_IP_ADDR	((192UL<<24)|(168<<16)|(2<<8)|112)

extern unsigned long download_len;
extern unsigned long download_addr;

int NetLoadFile(UINT32T addr, UINT32T give_ip, UINT32T a3, UINT32T a4)
{
	struct sk_buff *sendskb;
	UINT8T* senddata;
	
	unsigned char eth_addr[ETH_ALEN];	
	unsigned char *s;
	int i;
	char *p;
	give_ip = LOCAL_IP_ADDR;
	s = (unsigned char *)&give_ip;
	
	uart_printf("Mini TFTP Server 1.0 (IP : %d.%d.%d.%d PORT: %d)\n", s[3], s[2], s[1], s[0], TFTP);		
	uart_printf("Type tftp -i %d.%d.%d.%d put filename at the host PC\n", s[3], s[2], s[1], s[0]);

	eth_init();		
	eth_get_addr(eth_addr);		
	ip_init(give_ip);
	udp_init();
		
	arp_add_entry(eth_addr, give_ip);	

	TftpLoadEnd  = 0;
	TftpPutMark  = 0;
	TftpPutBegin = 0;
	
	download_addr = 0x30008000;
	download_len = 0;
	/*uart_printf("befort TftpLoadEnd 1\n");
	while (!TftpLoadEnd) {		
		net_handle();
		if(TftpPutBegin) {
			uart_printf("Starting the TFTP download...\n");
			TftpPutBegin = 0;
		}
		if(TftpPutMark) {
			uart_sendbyte('.');
			TftpPutMark = 0;
		}
	}
  uart_printf("after TftpLoadEnd 1\n");
	uart_printf("before TftpLoadEnd 2\n");
	if(TftpLoadEnd) {
		uart_printf("\ndownload 0x%x bytes to 0x%08x\n\n", download_len, download_addr);
	p=(char *)download_addr;
	for(i=0;i<download_len;i++)
		uart_printf("%c",p[i]);
    uart_printf("\nPress any key to continue...\n");
    while(!uart_getkey());
	return download_len;
	}
  uart_printf("after TftpLoadEnd 2\n");*/
	uart_printf("before net_handle\n");
	while(1)
	{
	net_handle();
	rtc_gettime(3);
	sendskb = alloc_skb(ETH_FRAME_LEN);
 	udp_skb_reserve(sendskb);
 	senddata = (UINT8T *)skb_put(sendskb, strlen(format_time)*sizeof(UINT8T));
 	strcpy(senddata, format_time);
	uart_printf("send length:%d %d content :%s\n", strlen(senddata),strlen(format_time), senddata);
 	udp_send_length(sendskb, REMOTE_IP_ADDR, 691, 6666,strlen(senddata));
	delay(4000);
	}
	uart_printf("after net_handle\n");
	return 0;
}



